--[[
MIT License

Copyright (c) 2023 Anggara Yama Putra

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
--]]
--[[
https://github.com/scandum/base252/blob/master/LICENSE.md

ISC License

Copyright (c) 2020 Igor van den Hoven <ivdhoven@gmail.com>

Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
]]
-- Globals
AnggaraNothing = AnggaraNothing or {}
do
end

-- module: Base252
do
  local root = {}

  local strbyte = string.byte
  local strchar = string.char
  local tablepack = table.pack
  local tableunpack = table.unpack

  local function create_iter (len, step, ...)
    step = step or 1
    local args
    local unpack = tableunpack
    if select('#', ...) == 1 then
      local first = ...
      local first_type = type( first )
      if first_type == 'table' then
        args, len = first, len or #first
      elseif first_type == 'string' then
        args, len = first, len or #first
        unpack = strbyte
      end
    end
    args = args or tablepack( ... )
    len = len or args.n
    local pos, nextpos = 1, 1
    return function ()
      if nextpos > len then
        return
      end
      pos, nextpos = nextpos, nextpos + step
      return unpack(args, pos, nextpos-1)
    end, len
  end

  local MAX_BUFFER_SIZE = 8192

  local encode
  do
    local ILLEGALS = {
      [0] = 245, -- null
      [34] = 245, -- double quote
      [92] = 246, -- backslash
      -- reserved
      [245] = 248,
      [246] = 248,
      [247] = 248,
      [248] = 248,
    }

    local echunks = {}
    encode = function (...)
      local i = 1
      for b1 in create_iter( nil, nil, ... ) do
        local illegal_code = ILLEGALS[b1]
        if illegal_code then
          echunks[i] = illegal_code
          i = i + 1
          echunks[i] = 128 + b1 % 64
        else
          echunks[i] = b1
        end
        i = i + 1
      end
      i = i - 1

      local result = echunks
      if #echunks > MAX_BUFFER_SIZE then
        echunks = {}
      end
      return tableunpack(result, 1, i)
    end
  end

  local decode
  do
    local RESERVED = {
      [245] = 0,
      [246] = 64,
      [247] = 128,
      [248] = 192,
    }

    local dchunks = {}
    decode = function (...)
      local i = 1
      local iter = create_iter( nil, nil, ... )
      for b1 in iter do
        local add = RESERVED[b1]
        if add then
          dchunks[i] = add + iter() % 64
        else
          dchunks[i] = b1
        end
        i = i + 1
      end
      i = i - 1

      local result = dchunks
      if #dchunks > MAX_BUFFER_SIZE then
        dchunks = {}
      end
      return tableunpack(result, 1, i)
    end
  end

  function root.encode_as_string (...)
    return strchar( encode(...) )
  end

  function root.decode_as_string (...)
    return strchar( decode(...) )
  end

  root.encode = encode
  root.decode = decode
  AnggaraNothing.Base252 = root

  --[[ tests
  do
    local samples = {
      {"hello world!", 'hello world!',},
      {"hello world!\x00", 'hello world!\245\128',},
      {"hello world!!", 'hello world!!'},
      {"hello world!!\x00", 'hello world!!\245\128',},
      {"мир привет!", 'мир привет!',},
      {"мир привет!\x00", 'мир привет!\245\128',},
      {"мир привет!!", 'мир привет!!'},
      {"мир привет!!\x00", 'мир привет!!\245\128'},
      {"🌲🌳🌾🌽", '🌲🌳🌾🌽'},
      {'🌲"🌳🌾\x00🌽', '🌲\245\162🌳🌾\245\128🌽'},
      {'a\x00b"c\\d\245e\246f\247g\248', 'a\245\128b\245\162c\246\156d\248\181e\248\182f\248\183g\248\184'},
    }

    local tableconcat = table.concat
    local debug = log or print
    local rencode, rdecode, rencode_as_string,
    rdecode_as_string = root.encode, root.decode, root.encode_as_string, root.decode_as_string

    for _,v in ipairs(samples) do
      local textstr, outstr = tableunpack( v )
      local textbytes, outbytes = tablepack(strbyte(textstr, 1, -1)), tablepack(strbyte(outstr, 1, -1))

      debug( '---Bytes Table---' )
      local encoded = {rencode( textbytes )}
      local encodedstr = strchar( tableunpack(encoded) )
      debug( textstr, ' : ', tableconcat(encoded, ',') )
      assert( encodedstr == outstr, '[tb] encoder failed' )

      local decoded = {rdecode( outbytes )}
      local decodedstr = strchar( tableunpack(decoded) )
      debug( textstr, ' : ', tableconcat(decoded, ',') )
      assert( decodedstr == textstr, '[tb] decoder failed' )

      decoded = {rdecode( encoded )}
      decodedstr = strchar( tableunpack(decoded) )
      debug( decodedstr, ' : ', tableconcat(decoded, ',') )
      assert( decodedstr == textstr, '[tb] roundtrip failed' )

      debug( '---String---' )
      encodedstr = rencode_as_string( textstr )
      debug( textstr, ' : ', encodedstr )
      assert( encodedstr == outstr, '[str] encoder failed' )

      decodedstr = rdecode_as_string( outbytes )
      debug( textstr, ' : ', decodedstr )
      assert( decodedstr == textstr, '[str] decoder failed' )

      decodedstr = rdecode_as_string( encodedstr )
      debug( encodedstr, ' : ', decodedstr )
      assert( decodedstr == textstr, '[str] roundtrip failed' )

      debug( '---Varags---' )
      encoded = {rencode( tableunpack(textbytes) )}
      encodedstr = rencode_as_string( tableunpack(textbytes) )
      debug( textstr, ' : ', tableconcat(encoded, ',') )
      assert( encodedstr == outstr, '[va] encoder failed' )

      decoded = {rdecode( tableunpack(outbytes) )}
      decodedstr = rdecode_as_string( tableunpack(outbytes) )
      debug( textstr, ' : ', tableconcat(decoded, ',') )
      assert( decodedstr == textstr, '[va] decoder failed' )

      decoded = {rdecode( tableunpack(encoded) )}
      decodedstr = strchar( tableunpack(decoded) )
      debug( decodedstr, ' : ', tableconcat(decoded, ',') )
      assert( decodedstr == textstr, '[va] roundtrip failed' )
    end
  end
  --]]
end
